package repository

import (
	"time"

	"gorm.io/gorm"

	"pool/pool_backend/internal/models"
	"pool/pool_backend/pkg/logger"
)

// ClaimRepository Claim仓库接口
type ClaimRepository interface {
	// CreateClaimRecord 创建Claim记录
	CreateClaimRecord(record *models.ClaimRecord) error
	// GetClaimRecords 获取用户的Claim记录
	GetClaimRecords(address string) ([]*models.ClaimResponse, error)
	// CreateCheckInRecord 创建Check-In记录
	CreateCheckInRecord(record *models.CheckInRecord) error
	// GetLastCheckInTime 获取用户最后一次Check-In时间
	GetLastCheckInTime(address string) (time.Time, error)
	// GetTotalClaimed 获取总领取数量
	GetTotalClaimed() (int64, error)
}

// claimRepositoryImpl Claim仓库实现
type claimRepositoryImpl struct {
	db *gorm.DB
}

// NewClaimRepository 创建Claim仓库
func NewClaimRepository(db *gorm.DB) ClaimRepository {
	return &claimRepositoryImpl{db: db}
}

// CreateClaimRecord 创建Claim记录
func (r *claimRepositoryImpl) CreateClaimRecord(record *models.ClaimRecord) error {
	result := r.db.Create(record)
	if result.Error != nil {
		logger.ErrorF("Failed to create claim record: %v", result.Error)
		return result.Error
	}
	return nil
}

// GetClaimRecords 获取用户的Claim记录
func (r *claimRepositoryImpl) GetClaimRecords(address string) ([]*models.ClaimResponse, error) {
	var records []models.ClaimRecord
	result := r.db.Where("user_address = ?", address).Order("claim_time DESC").Find(&records)
	if result.Error != nil {
		logger.ErrorF("Failed to get claim records: %v", result.Error)
		return nil, result.Error
	}

	// 转换为ClaimResponse
	responses := make([]*models.ClaimResponse, len(records))
	for i, record := range records {
		responses[i] = &models.ClaimResponse{
			Amount:    record.Amount,
			ClaimTime: record.ClaimTime,
			Hash:      record.Hash,
		}
	}

	return responses, nil
}

// CreateCheckInRecord 创建Check-In记录
func (r *claimRepositoryImpl) CreateCheckInRecord(record *models.CheckInRecord) error {
	result := r.db.Create(record)
	if result.Error != nil {
		logger.ErrorF("Failed to create check-in record: %v", result.Error)
		return result.Error
	}
	return nil
}

// GetLastCheckInTime 获取用户最后一次Check-In时间
func (r *claimRepositoryImpl) GetLastCheckInTime(address string) (time.Time, error) {
	var record models.CheckInRecord
	result := r.db.Where("user_address = ?", address).Order("check_in_time DESC").First(&record)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return time.Time{}, nil // 返回零时间表示没有Check-In记录
		}
		logger.ErrorF("Failed to get last check-in time: %v", result.Error)
		return time.Time{}, result.Error
	}
	return record.CheckInTime, nil
}

// GetTotalClaimed 获取总领取数量
func (r *claimRepositoryImpl) GetTotalClaimed() (int64, error) {
	var total int64
	result := r.db.Model(&models.ClaimRecord{}).Select("COALESCE(SUM(amount), 0)").Scan(&total)
	if result.Error != nil {
		logger.ErrorF("Failed to get total claimed: %v", result.Error)
		return 0, result.Error
	}
	return total, nil
} 